package top.ibiji.shiro.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component()
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    long beginTime = 0;

    @Pointcut("@annotation(WebLog)")
    public void logPointCut() {
    }


    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        beginTime = System.currentTimeMillis();
        System.out.println("beginTime--->"+beginTime);

        WebLog annotationLog = getAnnotationLog(joinPoint);
        System.out.println(annotationLog.action());
        System.out.println(annotationLog.title());

    }

    @AfterReturning(returning = "object", pointcut = "logPointCut()")
    public void doAfterReturning(Object object) throws Throwable {
        System.out.println(System.currentTimeMillis());
        long time = System.currentTimeMillis() - beginTime;
        System.out.println("运行时长-->"+time);
    }


    //后置异常通知
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {

    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private static WebLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(WebLog.class);
        }
        return null;
    }

}
